<template>
  <div class="container">
    <div class="login-form">
      <div class="form_title">
        <span class="title_china">众安睿博算法视界配置管理系统</span>
      </div>
      <form @submit.prevent="onSubmit">
        <div class="form-group">
          <el-input
            v-model="userName"
            style="width: 100%"
            size="large"
            placeholder="请输入用户名称"
            :prefix-icon="User"
          />
        </div>
        <div class="form-group">
          <el-input
            v-model="passWord"
            style="width: 100%"
            size="large"
            placeholder="请输入登录密码"
            type="password"
            show-password
            :prefix-icon="Lock"
          />
        </div>
        <div class="form-group">
          <input v-model="rememberMe" id="rememberMe" type="checkbox" />
          <label for="rememberMe">记住密码</label>
        </div>
        <button type="submit" class="login-button">登录</button>
      </form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Lock, User } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import request from "@/utils/request";
import { useAuthStore } from "@/stores/user";
import { useAlgorStore } from "../stores/algorothm";

const userName = ref("");
const passWord = ref("");
const rememberMe = ref(false);
const router = useRouter();
const authStore = useAuthStore();
const algorStore = useAlgorStore();

onMounted(() => {
  const savedUsername = localStorage.getItem("username");
  const savedPassword = localStorage.getItem("password");
  if (savedUsername && savedPassword) {
    userName.value = savedUsername;
    passWord.value = savedPassword;
    rememberMe.value = true;
  }
  getAllAlgorithm();
});

const validatePasswordStrength = (password: string) => {
  const lengthCheck = password.length >= 8 && password.length <= 20;
  const complexityCheck = /(?=.*[a-z])(?=.*[A-Z])|(?=.*[a-z])(?=.*\d)|(?=.*[a-z])(?=.*[!@#$%^&*])|(?=.*[A-Z])(?=.*\d)|(?=.*[A-Z])(?=.*[!@#$%^&*])|(?=.*\d)(?=.*[!@#$%^&*])/.test(password);
  const noSequentialChars = !/(.)\1{2,}/.test(password); // 防止连续3个相同字符
  return lengthCheck && complexityCheck && noSequentialChars;
};
const emit = defineEmits(["close1"]);
const onSubmit = async () => {
  if (!userName.value) {
    ElMessage.error("请填写用户账号");
    return;
  }
  if (!passWord.value) {
    ElMessage.error("请填写登录密码");
    return;
  }
  if (!validatePasswordStrength(passWord.value)) {
    ElMessage.error("密码强度不符合要求，请包含8-20位字符且至少包含两种类型（大写字母、小写字母、数字、特殊字符）");
    return;
  }

  try {
    const res = await request.post("/user/login", {
      username: userName.value,
      password: passWord.value,
    });
    if (res.data.status !== "fail") {
      ElMessage.success("登录成功");
      emit("close1")
      localStorage.setItem("username", userName.value);
      localStorage.setItem("password", rememberMe.value ? passWord.value : "");
      localStorage.setItem("isLoggedIn", "true");
      authStore.setAuthData(res.data);
      getAllAlgorithm();

      // if (res.data.user?.roleID === 1) {
      //   router.push("/Administratorsheader");
      // } else {
      //   router.push("/");
      // }
    } else {
      ElMessage.error("用户名或密码不正确");
    }
  } catch (error) {
    ElMessage.error("登录失败，请稍后再试");
  }
};

const getAllAlgorithm = async () => {
  try {
    const res = await request.get("/algorithm/algorithmView");
    algorStore.setAlgorData(res.data);
  } catch (error) {
    ElMessage.error("获取算法数据失败");
  }
};
</script>

<style scoped>
.container {
  width:100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('/path/to/background-image.jpg') no-repeat center center;
  background-size: cover;
}
.login-form {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 10px;
  width: 300px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.form_title {
  font-size: 1.2em;
  margin-bottom: 25px;
  color: #313131;
  font-weight: 500;
  text-align: center;
}
.form-group {
  margin-bottom: 20px;
}
.login-button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.login-button:hover {
  background-color: #0056b3;
}
</style>
